//选择战役方式Layer，包括打电脑，单人，匹配，创建房间，进入房间，取消游戏

var loadBattle = {
	layer : null,
	status : 0,
	
	centerLabel : null,
	playerLeft : null,
	playerRight : null,
	menu : null,
	jumpingText : null,
	
	playAI : null,
	playSingle : null,
	playMatch : null,
	playBuildRoom : null,
	playEnterRoom : null,
	cancelPlay : null,
	
	Initialize : function(){
		this.status = 0;
	},
	
	SetAllManipulateEnable : function(enable){
		enable = enable || false;
		
		if (this.playAI != null)
			this.playAI.enabled = enable;
		if (this.playSingle != null)
			this.playSingle.enabled = enable;
		if (this.playMatch != null)
			this.playMatch.enabled = enable;
		if (this.playBuildRoom != null)
			this.playBuildRoom.enabled = enable;
		if (this.playEnterRoom != null)
			this.playEnterRoom.enabled = enable;
		if (this.cancelPlay != null)
			this.cancelPlay.enabled = enable;
	},

	startGameTimeoutHandle : null,
	
	//status :   0:none; 1:play mode select; 2:waiting player; 3:waiting game-start
	ShowStatus : function(status){
		if (status == loadBattle.status)
			return;
		loadBattle.status = status;

		loadBattle.StopStartGame();
		
		if (this.centerLabel != null){
			this.centerLabel.removeFromParent();
			this.centerLabel = null;
		}
		if (this.playerLeft != null){
			this.playerLeft.removeFromParent();
			this.playerLeft = null;
		}
		if (this.playerRight != null){
			this.playerRight.removeFromParent();
			this.playerRight = null;
		}
		if (this.menu != null){
			this.menu.removeFromParent();
			this.menu = null;
		}
		if (this.jumpingText != null){
			this.jumpingText.Stop();
			this.jumpingText = null;
		}
		
		this.playAI = null;
		this.playSingle = null;
		this.playMatch = null;
		this.playBuildRoom = null;
		this.playEnterRoom = null;
		this.cancelPlay = null;

		var winSize = cc.director.getWinSize();

		if (status == 1){
			//vs
			this.centerLabel = new cc.Sprite(resource.vs_png);
			this.centerLabel.attr({
				x : winSize.width * 0.5,
				y : winSize.height * 0.46,
				scale : 5,
				opacity : 0
			});
			this.layer.node.addChild(this.centerLabel);
			this.centerLabel.runAction(cc.fadeIn(0.6));
			this.centerLabel.runAction(cc.scaleTo(0.6, 1.5));

			//menus
			this.playAI = this.layer._CreateShortButton("对战AI",0,0,this.OnPlayAI);
			this.playSingle = this.layer._CreateShortButton("本机对战",0,0,this.OnPlaySingle);
			this.playMatch = this.layer._CreateShortButton("联网对战",0,0,this.OnPlayMatch);
			this.playBuildRoom = this.layer._CreateShortButton("创建房间",0,0,this.OnPlayBuildRoom);
			this.playEnterRoom = this.layer._CreateShortButton("加入房间",0,0,this.OnPlayEnterRoom);

			ArrangeHorizontal(winSize.width * 0.5, winSize.height * 0.11, winSize.width * 0.02,
					[ this.playAI, this.playSingle, this.playMatch, this.playBuildRoom, this.playEnterRoom ]);

			this.menu = cc.Menu.create(this.playAI, this.playSingle, this.playMatch, this.playBuildRoom, this.playEnterRoom);
			this.menu.attr({ x:0, y:0 });
			this.layer.node.addChild(this.menu);
			
		}else if (status == 2){
			//label
			var text = "正在等待其他玩家...";
			if (gameRoom != null && gameRoom.password == "default"){
				text = text + "\n\n房间号：" + gameRoom.id;
			}else{
				text = text + "\n\n预计等待时间： < 1 分钟";
			}
			this.centerLabel = this.layer._CreateBackgroundLabel(text,winSize.width * 0.5,winSize.height * 0.46);
			this.layer.node.addChild(this.centerLabel, 998);

			this.cancelPlay = this.layer._CreateShortButton("取消游戏",winSize.width * 0.5, winSize.height * 0.11,this.OnCancelGame);
			this.menu =  cc.Menu.create(this.cancelPlay);
			this.menu.attr({ x:0, y:0 });
			this.layer.node.addChild(this.menu);

		}else if (status = 3){
			var remainsec = 10;
			if (gameRoom.starttime != null){
				remainsec = 20 - (newDate().getTime() - gameRoom.starttime) * 0.001;
			}
			var showremainsec = Math.floor(remainsec);
			//label
			var text = "游戏即将开始...\n\n倒计时：" + showremainsec;
			this.centerLabel = this.layer._CreateBackgroundLabel(text,winSize.width * 0.5,winSize.height * 0.46);
			this.layer.node.addChild(this.centerLabel, 998);
			this.jumpingText = new JumpingText(this.centerLabel, "游戏即将开始...\n\n倒计时：#NUM0", [showremainsec + 1], [-1], showremainsec, 1.0);
			//no bad result of layer-destroy
			setTimeout(loadBattle.jumpingText.Start, (remainsec - showremainsec) * 1000);
			loadBattle.startGameTimeoutHandle = setTimeout(loadBattle.StartGame, remainsec * 1000);
			
			//menu
			var cancelPlay = this.layer._CreateShortButton("取消游戏",winSize.width * 0.5, winSize.height * 0.11,this.OnCancelGame);
			this.menu =  cc.Menu.create(cancelPlay);
			this.menu.attr({ x:0, y:0 });
			this.layer.node.addChild(this.menu);
			
			//players
			var users = JSON.parse(gameRoom.users);
			
			this.playerLeft = CreatePlayerSprite(users[0].name, users[0].rank);
			this.playerLeft.setPosition(- (this.playerLeft.width * 0.5), winSize.height * 0.46);
			this.playerLeft.runAction(cc.moveTo(0.4, (this.playerLeft.width * 0.5) + 24, winSize.height * 0.46));
			this.layer.node.addChild(this.playerLeft);
			
			this.playerRight = CreatePlayerSprite(users[1].name, users[1].rank);
			this.playerRight.setPosition(winSize.width + (this.playerRight.width * 0.5), winSize.height * 0.46);
			this.playerRight.runAction(cc.moveTo(0.4, winSize.width - (this.playerRight.width * 0.5) - 24, winSize.height * 0.46));
			this.layer.node.addChild(this.playerRight);
		}
	},
	
	StartGame : function(){
		if (this.jumpingText != null){
			this.jumpingText.Stop();
			this.jumpingText = null;
		}
		cc.director.runScene(campaignScene.Create());
	},
	
	StopStartGame : function(){
		if (loadBattle.startGameTimeoutHandle != null){
			clearTimeout(loadBattle.startGameTimeoutHandle);
			loadBattle.startGameTimeoutHandle = null;
		}
	},

	//========================== Play Local ========================
	OnPlayAI : function(sender){
		gameRoom = gameRoomEngine.CreateGameRoom(campaign,
				[userSet.gameUser, gameUserEngine.CreateAIGameUser()],
				[-1, -1]);
		loadBattle.ShowStatus(3);
	},

	OnPlaySingle : function(sender){
		gameRoom = gameRoomEngine.CreateGameRoom(campaign,
				[userSet.gameUser, gameUserEngine.CreateGameUser()],
				[-1, -1]);
		loadBattle.ShowStatus(3);
	},

	//========================== Play Match ========================
	OnPlayMatch : function(sender){
		if (userSet.user == null){
			messageBox.Show("\"匹配玩家\"需要登录服务器",this);
			return;
		}
		//TODO:
	},

	//========================== Build Room ========================
	OnPlayBuildRoom : function(sender){
		if (userSet.user == null){
			messageBox.Show("\"创建游戏房间\"需要登录服务器",this);
			return;
		}
		
		loadBattle.SetAllManipulateEnable(false);
		
		var room = gameRoomEngine.CreateGameRoom(campaign, [userSet.gameUser],[userSet.user.id]);
		netService.BuildRoom(userSet.user.id, JSON.stringify(room), loadBattle.BuildRoomHandler, 1);
	},
	
	BuildRoomHandler : function(text){
		loadBattle.SetAllManipulateEnable(true);
		if (text == null){
			messageBox.Show("创建房间：连接服务器失败! 请检查网络设置", loadBattle.layer);
			return;
		}
		if (text[0] != '{' || text[text.length - 1] != '}'){
			messageBox.Show("创建房间失败! 服务器异常", loadBattle.layer);
			return;
		}
		
		var room = JSON.parse(text);
		if (room == null || room.id < 0){
			messageBox.Show("创建房间失败! 服务器异常", loadBattle.layer);
			return;
		}
		
		gameRoom = room;
		loadBattle.RefreshLayer();
	},

	//========================== Enter Room ========================
	OnPlayEnterRoom : function(sender){
		if (userSet.user == null){
			messageBox.Show("\"进入游戏房间\"需要登录服务器",this);
			return;
		}

		inputBox.Show("请输入房间号","",loadBattle.layer,loadBattle.OnInputRoomidHandler);
	},
	
	OnInputRoomidHandler : function(value){
		var roomid = parseInt(value);
		if (isNaN(roomid)){
			messageBox.Show("输入的房间号应该是一个整数",this);
			return;
		}
		
		loadBattle.SetAllManipulateEnable(false);
		netService.EnterRoom(userSet.user.id, roomid, loadBattle.EnterRoomHandler, 1);
	},
	
	EnterRoomHandler : function(text){
		loadBattle.SetAllManipulateEnable(true);
		if (text == null){
			messageBox.Show("进入房间：连接服务器失败! 请检查网络设置", loadBattle.layer);
			return;
		}
		if (text[0] != '{' || text[text.length - 1] != '}'){
			messageBox.Show("进入房间失败! 服务器异常", loadBattle.layer);
			return;
		}
		
		var room = JSON.parse(text);
		if (room == null || room.id < 0){
			messageBox.Show("进入房间失败! 服务器异常", loadBattle.layer);
			return;
		}
		if (room.status < 0 || room.status > 3){
			messageBox.Show("进入房间失败! 房间状态异常", loadBattle.layer);
			return;
		}
		if (room.status == 1){
			messageBox.Show("进入房间失败! 游戏已开始", loadBattle.layer);
			return;
		}
		if (room.status == 2 || room.status == 3){
			messageBox.Show("进入房间失败! 游戏取消或已结束", loadBattle.layer);
			return;
		}
		gameRoom = room;
		loadBattle.RefreshLayer();
	},
	
	//========================== Cancel Room ========================
	OnCancelGame : function(sender){
		if (userSet.user == null){
			loadBattle.ShowStatus(1);
			return;
		}

		loadBattle.SetAllManipulateEnable(false);
		netService.CancelRoom(userSet.user.id, gameRoom.id, loadBattle.CancelGameHandler, 1);
	},
	
	CancelGameHandler : function(text){
		loadBattle.SetAllManipulateEnable(true);
		if (text == null){
			messageBox.Show("取消游戏：连接服务器失败! 请检查网络设置", loadBattle.layer);
			return;
		}
		
		if (text != "true"){
			messageBox.Show("取消游戏失败! 服务器异常", loadBattle.layer);
			return;
		}
		gameRoom.status = 3;
		loadBattle.RefreshLayer();
	},
	
	//========================== Get Room ========================
	_getRoomTimeoutHandle : null,
	StartGetRoom : function(){
		loadBattle._getRoomTimeoutHandle = setTimeout(loadBattle.GetRoom, 5.5 * 1000);
	},
	StopGetRoom : function(){
		if (loadBattle._getRoomTimeoutHandle != null){
			clearTimeout(loadBattle._getRoomTimeoutHandle);
			loadBattle._getRoomTimeoutHandle = null;
		}
	},
	
	GetRoom : function(){
		netService.GetRoom(userSet.user.id, gameRoom.id, loadBattle.GetRoomHandler, 1);
	},
	
	GetRoomHandler : function(text){
		if (text == null){
			messageBox.Show("获取房间信息：连接服务器失败! 请检查网络设置", loadBattle.layer);
			return;
		}
		if (text[0] != '{' || text[text.length - 1] != '}'){
			messageBox.Show("获取房间信息! 服务器异常", loadBattle.layer);
			return;
		}

		var room = JSON.parse(text);
		if (room == null || room.id < 0){
			messageBox.Show("获取房间信息失败! 服务器异常", loadBattle.layer);
			return;
		}
		gameRoom = room;
		loadBattle.RefreshLayer();
	},

	//========================== Refresh Layer ========================
	RefreshLayer : function(){
		if (gameRoom.status == 0){
			loadBattle.StartGetRoom();
			
			loadBattle.ShowStatus(2);

		}else if (gameRoom.status == 1){
			loadBattle.StartGetRoom();
			
			loadBattle.ShowStatus(3);

		}else{
			var tip = "游戏已" + (gameRoom.status == 2 ? "关闭" : "取消");
			messageBox.Show(tip, loadBattle.layer);
			loadBattle.ShowStatus(1);
		}
	},
};

var LoadBattleLayer = CanvasLayer.extend({
	ini : function(){
		loadBattle.layer = null;
		loadBattle.status = 0;
		loadBattle.centerLabel = null;
		loadBattle.playerLeft = null;
		loadBattle.playerRight = null;
		loadBattle.menu = null;
		loadBattle.playAI = null;
		loadBattle.playSingle = null;
		loadBattle.playMatch = null;
		loadBattle.playBuildRoom = null;
		loadBattle.playEnterRoom = null;
		loadBattle.cancelPlay = null;
		
		var winSize = cc.director.getWinSize();
		
		//title & map-info
		var title = cc.LabelTTF.create(campaign.title, "simhei", 64);
		title.attr({ x : winSize.width * 0.5, y : winSize.height * 0.88 });
		this.node.addChild(title);
		
		var tip = "[" + campaign.time_ref.time[0] + "-" + campaign.time_ref.time[1] + "-" + campaign.time_ref.time[2]
			+ "] [" + campaign.zone.xsize + "×" + campaign.zone.ysize
			+ "] [" + campaign.force[0].name + " VS " + campaign.force[1].name
			+ "] [Landforms:" + campaign.zone.landforms + "]";
		var labelTip = cc.LabelTTF.create(tip, "simhei", 28);
		labelTip.attr({ x : winSize.width * 0.5, y : winSize.height * 0.79, color : cc.color(225,225,225) });
		this.node.addChild(labelTip, 100);
		
		//left-panel && right-panel
		var leftNode = new cc.Node();
		leftNode.setPosition(winSize.width * (1.2), winSize.height * 0.46);
		var leftPanel = new cc.Scale9Sprite(resource.scale9halfwhite100100_png, cc.rect(0,0,100,100), cc.rect(8,8,84,84))
		leftPanel.setContentSize(winSize.width * 0.4, winSize.height * 0.5);
		leftPanel.setColor(cc.color(192,32,32));
		this.node.addChild(leftNode);
		leftNode.addChild(leftPanel);
		leftNode.runAction(cc.sequence(cc.delayTime(this.showDuration),cc.moveTo(0.5,
				winSize.width * (0.5-0.5*0.4) - 16, winSize.height * 0.46)));
		
		var rightNode = new cc.Node();
		rightNode.setPosition(winSize.width * (-0.2),winSize.height * 0.46);
		var rightPanel = new cc.Scale9Sprite(resource.scale9halfwhite100100_png, cc.rect(0,0,100,100), cc.rect(8,8,84,84))
		rightPanel.setContentSize(winSize.width * 0.4, winSize.height * 0.5);
		rightPanel.setColor(cc.color(32,32,192));
		this.node.addChild(rightNode);
		rightNode.addChild(rightPanel);
		rightNode.runAction(cc.sequence(cc.delayTime(this.showDuration),cc.moveTo(0.5,
				winSize.width * (0.5+0.5*0.4) + 16, winSize.height * 0.46)));
		
		//flags
		var flag0 = new cc.Sprite(campaign.force[0].flag);
		flag0.attr({ x:0, y:0.5 * leftPanel.height, scale : 3});
		leftNode.addChild(flag0,1);

		var flag1 = new cc.Sprite(campaign.force[1].flag);
		flag1.attr({ x:0, y:0.5 * rightPanel.height, scale : 3});
		rightNode.addChild(flag1,1);

		//units
		var troopidArray1 = [];
		var troopidArray2 = [];
		for (var troopid = 0; troopid < campaign.troop.length; troopid++){
			if (campaign.troop[troopid].force == 0){
				troopidArray1[troopidArray1.length] = troopid;
			}else{
				troopidArray2[troopidArray2.length] = troopid;
			}
		}
		var troopSqrtCount1 = Math.ceil(Math.sqrt(troopidArray1.length));
		var colDiv1 = leftPanel.width / (troopSqrtCount1 + 1);
		var rowDiv1 = leftPanel.height / (troopSqrtCount1 + 1);
		var troopSqrtCount2 = Math.ceil(Math.sqrt(troopidArray2.length));
		var colDiv2 = rightPanel.width / (troopSqrtCount2 + 1);
		var rowDiv2 = rightPanel.height / (troopSqrtCount2 + 1);
		
		for (var idx = 0; idx < troopidArray1.length; idx++){
			var troopid = troopidArray1[idx];
			var rowid = Math.floor(idx / troopSqrtCount1);
			var colid = Math.floor(idx % troopSqrtCount1);
			var sprite = new cc.Sprite(campaign.troop_type[campaign.troop[troopid].troop_type].base_image);
			orientationEngine.SetOrientation(sprite, 3);
			sprite.setPosition(
					-0.5 * leftPanel.width + (colid + 1) * colDiv1,
					0.5 * leftPanel.height - (rowid + 1) * rowDiv1);
			leftNode.addChild(sprite);
		}
		for (var idx = 0; idx < troopidArray2.length; idx++){
			var troopid = troopidArray2[idx];
			var rowid = Math.floor(idx / troopSqrtCount2);
			var colid = Math.floor(idx % troopSqrtCount2);
			var sprite = new cc.Sprite(campaign.troop_type[campaign.troop[troopid].troop_type].base_image);
			orientationEngine.SetOrientation(sprite, 0);
			sprite.setPosition(
					-0.5 * rightPanel.width + (colid + 1) * colDiv2,
					0.5 * rightPanel.height - (rowid + 1) * rowDiv2);
			rightNode.addChild(sprite);
		}
	},
	
	destroy : function(){
		
		loadBattle.StopStartGame();

		if (loadBattle.status > 1 && userSet.user != null){
			loadBattle.StopGetRoom();
			netService.CancelRoom(userSet.user.id, gameRoom.id, null, 2);
		}
		
		if (loadBattle.jumpingText != null){
			loadBattle.jumpingText.Stop();
			loadBattle.jumpingText = null;
		}
	},
	
	_CreateBackgroundLabel : function(text,xpos,ypos){
		var label = cc.LabelTTF.create(text, "simhei", 36);
		label.attr({x:xpos, y:ypos});
		var labelBackground = new cc.Scale9Sprite(resource.scale9halfblack100100_png, cc.rect(0,0,100,100), cc.rect(8,8,84,84));
		labelBackground.setContentSize(label.width + 24, label.height + 24);
		labelBackground.attr({
			x : 0.5 * label.width,
			y : 0.5 * label.height
		});
		label.addChild(labelBackground, -1);
		return label;
	},
	
	_CreateShortButton : function(text,xpos,ypos,callback){
		var button = new cc.MenuItemImage(resource.ctrlbtnNormalS_png,resource.ctrlbtnDownS_png, resource.ctrlbtnDisableS_png, callback, this);
		button.setPosition(xpos, ypos);
		button.setScale(1.5);
		var label = cc.LabelTTF.create(text, "simhei", 36);
		label.setPosition(button.width * 0.5, button.height * 0.5);
		label.setColor(cc.color(0,0,0));
		label.setScale(0.5);
		button.addChild(label);
		return button;
	},
});